<template>
    <div class="main-container">
        <!-- 页面标题 -->
        <div class="title-container">
            <h2 class="title">个人信息管理</h2>
        </div>

        <!-- 个人信息卡片 -->
        <div class="profile-card">
            <div class="profile-header">
                <div class="avatar-section">
                    <div class="avatar-container">
                        <img :src="userProfile.avatar || '/default-avatar.png'" 
                             :alt="userProfile.nickname || userProfile.username" 
                             class="avatar">
                        <div class="avatar-upload-overlay" @click="triggerAvatarUpload">
                            <i class="fas fa-camera"></i>
                            <span>更换头像</span>
                        </div>
                    </div>
                    <input ref="avatarInput" 
                           type="file" 
                           accept="image/*" 
                           @change="handleAvatarUpload" 
                           style="display: none;">
                </div>
                
                <div class="user-info">
                    <h3 class="username">{{ userProfile.username }}</h3>
                    <p class="join-time">加入时间：{{ formatDate(userProfile.joinTime) }}</p>
                    <div class="user-stats">
                        <div class="stat-item">
                            <span class="stat-value">{{ userProfile.totalArticles || 0 }}</span>
                            <span class="stat-label">发布文章</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-value">{{ userProfile.totalViews || 0 }}</span>
                            <span class="stat-label">总浏览量</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-value">{{ userProfile.totalLikes || 0 }}</span>
                            <span class="stat-label">获得点赞</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑表单 -->
        <div class="form-card">
            <h3 class="form-title">编辑个人信息</h3>
            
            <el-form :model="editForm" 
                     :rules="formRules" 
                     ref="editFormRef" 
                     label-width="100px"
                     class="edit-form">
                
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="editForm.nickname" 
                              placeholder="请输入昵称"
                              maxlength="60"
                              show-word-limit />
                </el-form-item>

                <el-form-item label="个人简介" prop="bio">
                    <el-input v-model="editForm.bio" 
                              type="textarea" 
                              :rows="4"
                              placeholder="请输入个人简介"
                              maxlength="500"
                              show-word-limit />
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <div class="email-input-group">
                        <el-input v-model="editForm.email" 
                                  placeholder="请输入邮箱"
                                  :disabled="emailVerified" />
                        <el-button v-if="!emailVerified" 
                                   type="primary" 
                                   size="small"
                                   :disabled="!editForm.email || sendingCode"
                                   :loading="sendingCode"
                                   @click="sendEmailVerificationCode">
                            {{ sendingCode ? '发送中...' : '发送验证码' }}
                        </el-button>
                        <span v-else class="verified-badge">
                            <i class="fas fa-check-circle"></i> 已验证
                        </span>
                    </div>
                </el-form-item>

                <el-form-item v-if="showVerificationInput" label="验证码" prop="verificationCode">
                    <div class="verification-input-group">
                        <el-input v-model="editForm.verificationCode" 
                                  placeholder="请输入邮箱验证码"
                                  maxlength="6" />
                        <el-button type="success" 
                                   size="small"
                                   :loading="verifying"
                                   @click="verifyEmailCode">
                            {{ verifying ? '验证中...' : '验证' }}
                        </el-button>
                    </div>
                </el-form-item>

                <!-- 暂时隐藏手机号字段 -->
                <!-- <el-form-item label="手机号" prop="phone">
                    <el-input v-model="editForm.phone" 
                              placeholder="请输入手机号" />
                </el-form-item> -->

                <el-form-item>
                    <el-button type="primary" 
                               :loading="saving"
                               @click="saveProfile">
                        {{ saving ? '保存中...' : '保存' }}
                    </el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 登录日志 -->
        <div class="logs-card">
            <h3 class="form-title">登录记录</h3>
            
            <el-table :data="loginLogs" 
                      v-loading="loadingLogs"
                      style="width: 100%">
                <el-table-column prop="loginTime" 
                                 label="登录时间" 
                                 width="180"
                                 :formatter="formatLoginTime" />
                <el-table-column prop="loginType" 
                                 label="登录方式" 
                                 width="120"
                                 :formatter="formatLoginType" />
                <el-table-column prop="ipAddress" 
                                 label="IP地址" 
                                 width="150" />
                <el-table-column prop="userAgent" 
                                 label="设备信息" 
                                 show-overflow-tooltip />
                <el-table-column prop="success" 
                                 label="状态" 
                                 width="80">
                    <template #default="scope">
                        <el-tag :type="scope.row.success ? 'success' : 'danger'">
                            {{ scope.row.success ? '成功' : '失败' }}
                        </el-tag>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="logsPagination.current"
                               v-model:page-size="logsPagination.size"
                               :total="logsPagination.total"
                               :page-sizes="[10, 20, 50]"
                               layout="total, sizes, prev, pager, next, jumper"
                               @size-change="handleLogsSizeChange"
                               @current-change="handleLogsCurrentChange" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCurrentUserProfile, updateUserProfileV2, uploadAvatar, getUserLoginLogs, sendEmailCode, bindEmail } from '@/api/admin/userprofile'

// 数据定义
const userProfile = ref({})
const editForm = reactive({
    nickname: '',
    bio: '',
    email: '',
    phone: '',
    verificationCode: ''
})

const loginLogs = ref([])
const logsPagination = reactive({
    current: 1,
    size: 10,
    total: 0
})

// 状态定义
const saving = ref(false)
const sendingCode = ref(false)
const verifying = ref(false)
const loadingLogs = ref(false)
const showVerificationInput = ref(false)
const emailVerified = computed(() => userProfile.value.emailVerified || userProfile.value.email_verified)

// 表单引用
const editFormRef = ref()
const avatarInput = ref()

// 表单验证规则
const formRules = {
    nickname: [
        { max: 60, message: '昵称长度不能超过60个字符', trigger: 'blur' }
    ],
    bio: [
        { max: 500, message: '个人简介长度不能超过500个字符', trigger: 'blur' }
    ],
    email: [
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
        { max: 100, message: '邮箱长度不能超过100个字符', trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ]
}

// 页面加载
onMounted(() => {
    loadUserProfile()
    loadLoginLogs()
})

// 加载用户信息
const loadUserProfile = async () => {
    try {
        const res = await getCurrentUserProfile()
        if (res.success) {
            userProfile.value = res.data
            // 填充编辑表单
            editForm.nickname = res.data.nickname || ''
            editForm.bio = res.data.bio || ''
            editForm.email = res.data.email || ''
            editForm.phone = res.data.phone || ''
        } else {
            ElMessage.error(res.message || '获取用户信息失败')
        }
    } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
    }
}

// 保存个人信息
const saveProfile = async () => {
    if (!editFormRef.value) return
    
    try {
        await editFormRef.value.validate()
        saving.value = true
        
        const res = await updateUserProfileV2(editForm)
        if (res.success) {
            ElMessage.success('保存成功')
            loadUserProfile() // 重新加载用户信息
        } else {
            ElMessage.error(res.message || '保存失败')
        }
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
    } finally {
        saving.value = false
    }
}

// 重置表单
const resetForm = () => {
    editForm.nickname = userProfile.value.nickname || ''
    editForm.bio = userProfile.value.bio || ''
    editForm.email = userProfile.value.email || ''
    editForm.phone = userProfile.value.phone || ''
    editForm.verificationCode = ''
    showVerificationInput.value = false
    
    if (editFormRef.value) {
        editFormRef.value.clearValidate()
    }
}

// 触发头像上传
const triggerAvatarUpload = () => {
    avatarInput.value.click()
}

// 处理头像上传
const handleAvatarUpload = async (event) => {
    const file = event.target.files[0]
    if (!file) return
    
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
        ElMessage.error('请选择图片文件')
        return
    }
    
    // 验证文件大小（限制为2MB）
    if (file.size > 2 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过2MB')
        return
    }
    
    try {
        const formData = new FormData()
        formData.append('file', file)
        
        const res = await uploadAvatar(formData)
        if (res.success) {
            ElMessage.success('头像上传成功')
            loadUserProfile() // 重新加载用户信息
        } else {
            ElMessage.error(res.message || '头像上传失败')
        }
    } catch (error) {
        console.error('头像上传失败:', error)
        ElMessage.error('头像上传失败')
    }
}

// 发送邮箱验证码
const sendEmailVerificationCode = async () => {
    if (!editForm.email) {
        ElMessage.error('请先输入邮箱')
        return
    }
    
    try {
        sendingCode.value = true
        const res = await sendEmailCode({
            email: editForm.email,
            type: 4 // 绑定邮箱
        })
        
        if (res.success) {
            ElMessage.success('验证码发送成功，请查收邮件')
            showVerificationInput.value = true
        } else {
            ElMessage.error(res.message || '验证码发送失败')
        }
    } catch (error) {
        console.error('发送验证码失败:', error)
        ElMessage.error('发送验证码失败')
    } finally {
        sendingCode.value = false
    }
}

// 验证邮箱验证码
const verifyEmailCode = async () => {
    if (!editForm.verificationCode) {
        ElMessage.error('请输入验证码')
        return
    }
    
    try {
        verifying.value = true
        const res = await bindEmail(editForm.email, editForm.verificationCode)
        
        if (res.success) {
            ElMessage.success('邮箱绑定成功')
            showVerificationInput.value = false
            editForm.verificationCode = ''
            loadUserProfile() // 重新加载用户信息
        } else {
            ElMessage.error(res.message || '验证码错误')
        }
    } catch (error) {
        console.error('验证邮箱失败:', error)
        ElMessage.error('验证邮箱失败')
    } finally {
        verifying.value = false
    }
}

// 加载登录日志
const loadLoginLogs = async () => {
    try {
        loadingLogs.value = true
        const res = await getUserLoginLogs({
            page: logsPagination.current,
            size: logsPagination.size
        })
        
        if (res.success) {
            loginLogs.value = res.data.records || []
            logsPagination.total = res.data.total || 0
        } else {
            ElMessage.error(res.message || '获取登录记录失败')
        }
    } catch (error) {
        console.error('获取登录记录失败:', error)
        ElMessage.error('获取登录记录失败')
    } finally {
        loadingLogs.value = false
    }
}

// 处理分页大小变化
const handleLogsSizeChange = (size) => {
    logsPagination.size = size
    logsPagination.current = 1
    loadLoginLogs()
}

// 处理当前页变化
const handleLogsCurrentChange = (page) => {
    logsPagination.current = page
    loadLoginLogs()
}

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '-'
    return new Date(dateStr).toLocaleString('zh-CN')
}

// 格式化登录时间
const formatLoginTime = (row, column, cellValue) => {
    return formatDate(cellValue)
}

// 格式化登录方式
const formatLoginType = (row, column, cellValue) => {
    const typeMap = {
        1: '用户名密码',
        2: '邮箱验证码',
        3: '手机验证码'
    }
    return typeMap[cellValue] || '未知'
}
</script>

<style scoped>
.main-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
    background: transparent;
    min-height: 100vh;
}

.title-container {
    margin-bottom: 20px;
}

.title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
}

.profile-card, .form-card, .logs-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    padding: 24px;
}

.profile-header {
    display: flex;
    align-items: flex-start;
    gap: 24px;
}

.avatar-section {
    flex-shrink: 0;
}

.avatar-container {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    overflow: hidden;
    cursor: pointer;
}

.avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: white;
    opacity: 0;
    transition: opacity 0.3s;
    font-size: 14px;
}

.avatar-container:hover .avatar-upload-overlay {
    opacity: 1;
}

.avatar-upload-overlay i {
    font-size: 24px;
    margin-bottom: 4px;
}

.user-info {
    flex: 1;
}

.username {
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
}

.join-time {
    color: #909399;
    margin: 0 0 16px 0;
}

.user-stats {
    display: flex;
    gap: 32px;
}

.stat-item {
    text-align: center;
}

.stat-value {
    display: block;
    font-size: 24px;
    font-weight: 600;
    color: #409EFF;
}

.stat-label {
    display: block;
    font-size: 14px;
    color: #909399;
    margin-top: 4px;
}

.form-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 20px 0;
    border-bottom: 2px solid #409EFF;
    padding-bottom: 8px;
}

.edit-form {
    max-width: 600px;
}

.email-input-group, .verification-input-group {
    display: flex;
    gap: 12px;
    align-items: center;
}

.email-input-group .el-input, .verification-input-group .el-input {
    flex: 1;
}

.verified-badge {
    color: #67C23A;
    font-size: 14px;
    white-space: nowrap;
}

.verified-badge i {
    margin-right: 4px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

/* 暗黑模式适配 */
.dark .title {
    color: #e5e7eb;
}

.dark .profile-card, 
.dark .form-card, 
.dark .logs-card {
    background: #374151;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
}

.dark .username {
    color: #e5e7eb;
}

.dark .join-time {
    color: #9ca3af;
}

.dark .stat-label {
    color: #9ca3af;
}

.dark .form-title {
    color: #e5e7eb;
    border-bottom-color: #3b82f6;
}

.dark .verified-badge {
    color: #10b981;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .main-container {
        padding: 16px;
    }
    
    .profile-header {
        flex-direction: column;
        align-items: center;
        text-align: center;
    }
    
    .user-stats {
        justify-content: center;
    }
    
    .edit-form {
        max-width: none;
    }
    
    .email-input-group, .verification-input-group {
        flex-direction: column;
        align-items: stretch;
    }
}
</style>
